package com.dst.java_demo.core;

import com.dst.java_demo.common.CommonResponse;
import com.dst.java_demo.core.configuration.ExceptionCodeConfiguration;
import com.dst.java_demo.exception.ServerException;
import com.dst.java_demo.util.ResponseDataUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import javax.servlet.http.HttpServletRequest;
import java.sql.SQLIntegrityConstraintViolationException;
import java.util.List;

/**
 * @Author: LiJian
 * @Date: 2021/1/15 16:53
 */
@ControllerAdvice
@ResponseBody
public class GlobalExceptionAdvice {

    final Integer SERVER_ERROR_CODE = 9999;

    @Autowired
    private ExceptionCodeConfiguration codeConfiguration;

    @ExceptionHandler(value = Exception.class)
    public String handleException(HttpServletRequest req, Exception e) {
        e.printStackTrace();
        CommonResponse commonResponse = new CommonResponse(SERVER_ERROR_CODE, codeConfiguration.getMessage(SERVER_ERROR_CODE));
        return ResponseDataUtil.returnResult(commonResponse);
    }

    @ExceptionHandler(ServerException.class)
    public String handleServerException(HttpServletRequest req, ServerException e) {
        e.printStackTrace();
        CommonResponse commonResponse = new CommonResponse(e.getCode(), codeConfiguration.getMessage(e.getCode()));
        return ResponseDataUtil.returnResult(commonResponse);
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public CommonResponse handleBeanValidation(HttpServletRequest req, MethodArgumentNotValidException e) {

        List<ObjectError> errors = e.getBindingResult().getAllErrors();
        String message = this.formatAllErrorMessages(errors);

        return new CommonResponse(10001, message);
    }

    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public CommonResponse handleConstraintException(HttpServletRequest req, SQLIntegrityConstraintViolationException e) {
        String message = e.getMessage();

        return new CommonResponse(10001, message);
    }



    private String formatAllErrorMessages(List<ObjectError> errors) {
        StringBuffer errorMsg = new StringBuffer();
        errors.forEach(error ->
                errorMsg.append(error.getDefaultMessage()).append(';')
        );
        return errorMsg.toString();
    }
}
